package web.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;;
import web.bo.ScreenUploadRecordBo;
import web.common.CutPageBean;
import web.common.Result;
import web.entity.ScreenUploadSearchBo;
import web.entity.Security_UserDetail;
import web.entity.admin.user.ScreenUploadEntity;
import web.mapper.ScreenUploadMysqlMapper;
import web.service.ScreenUploadService;
import web.utils.RandomUtils;

import java.io.File;
import java.util.List;

/**
 * ScreenUploadServiceImpl
 */

@Service
public class ScreenUploadServiceImpl implements ScreenUploadService {

    @Autowired
    private ScreenUploadMysqlMapper  scMapper;


    @Value("${filePath.ScreenPath}")
    private String ScreenPath;


    @Override
    public CutPageBean<ScreenUploadEntity> getList(Integer page, Integer pageSize, String keyWord) {
        ScreenUploadSearchBo searchBo =new ScreenUploadSearchBo();
        searchBo.setPage(page);
        searchBo.setPageSize(pageSize);
        searchBo.setStart(page,pageSize);
        searchBo.setName(keyWord);
        List<ScreenUploadEntity> res = scMapper.getList(searchBo);
        Integer count = scMapper.count(searchBo);
        CutPageBean<ScreenUploadEntity> cutPage=new CutPageBean<>();
        cutPage.initCutPage(count, searchBo.getPageSize(), res);
        return cutPage;
    }

    public List<ScreenUploadEntity> getListALL() {
        List<ScreenUploadEntity> res = scMapper.getListALL();
        return res;
    }

    /**
     * 保存
     * @param recordBo 上传信息
     * @return Result
     */
    @Override
    public Result save(MultipartFile filePicture,ScreenUploadRecordBo recordBo) {
        Boolean flag =this.loadFile(filePicture);
        if( flag== false){
            return Result.fail("存在相同文件");
        }

        //UsernamePasswordAuthenticationToken authentication =
        //        (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        //Security_UserDetail user = (Security_UserDetail) authentication.getPrincipal();
        //String accountAdmin = user.getUserDo().getAccount();
        String accountAdmin ="admin";
        String fileName = filePicture.getOriginalFilename();
        ScreenUploadEntity entity = new ScreenUploadEntity();
        entity.setName(recordBo.getName());
        entity.setFilePath(recordBo.getFilePath());
        entity.setFileName(fileName);
        entity.setCreateTime(RandomUtils.nowStr(""));
        entity.setCreateUser(accountAdmin);
        entity.setDisplay(recordBo.getDisplay());
        entity.setLink(recordBo.getLink());

        int result =  scMapper.insert(entity);

        if (result==1){
            return Result.succ("保存成功！");
        }

        return Result.fail("保存失败！");
    }

    /**
     * 修改
     * @param recordBo 上传信息
     * @return Result
     */
    @Override
    public Result edit(MultipartFile filePicture,ScreenUploadRecordBo recordBo) {
        String fileName = recordBo.getFileName();

        if (filePicture != null && !filePicture.isEmpty()) { //文件不为空，必须加条件判断
            Boolean flag = this.loadFile(filePicture);
            if (flag == false) {
                return Result.fail("存在相同文件");
            }
            fileName = filePicture.getOriginalFilename();
        }

//        UsernamePasswordAuthenticationToken authentication =
//                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
//        Security_UserDetail user = (Security_UserDetail) authentication.getPrincipal();
//        String accountAdmin = user.getUserDo().getAccount();
        String accountAdmin ="admin";
        ScreenUploadEntity entity = scMapper.selectById(recordBo.getId());
        if (entity==null){
            return Result.fail("修改失败！");
        }

        entity.setName(recordBo.getName());
        entity.setFilePath(recordBo.getFilePath());
        entity.setFileName(fileName);
        entity.setEditTime(RandomUtils.nowStr(""));
        entity.setEditUser(accountAdmin);
        entity.setDisplay(recordBo.getDisplay());
        entity.setLink(recordBo.getLink());

        int result =  scMapper.updateById(entity);

        if (result==1)
            return Result.succ("修改成功！");

        return Result.fail("修改失败！");
    }

    /**
     * 删除
     *
     * @param id 个人资料id
     * @return Result
     */
    @Override
    public Result delete(Integer id) {

        ScreenUploadEntity scEntity = scMapper.selectById(id);

        String filePath = ScreenPath;
        //删除文件
        web.utils.FileUtil.deleteFile(filePath+scEntity.getFileName());

        //删除MySQL表记录
        int result = scMapper.deleteById(id);

        if (result==1)
            return Result.succ("删除文件成功！");

        return Result.fail("删除文件失败！");

    }

    /**
     * 是否存在相同文件
     * @param filePicture
     * @return
     */
    public Boolean loadFile(MultipartFile filePicture) {

        String fileName = filePicture.getOriginalFilename();
        File file = new File(ScreenPath + "//" + fileName);
        if (file.exists()) {
            return false;
        }
        String filePath = null;
        if (fileName.split("\\.")[1].equals("jpg")|| fileName.split("\\.")[1].equals("png") || fileName.split("\\.")[1].equals("gif")|| fileName.split("\\.")[1].equals("bmp")|| fileName.split("\\.")[1].equals("jpeg")) {
            filePath = new File(ScreenPath).toString();
        }

        try {
            //执行保存(文件,目录,文件名)
            web.utils.FileUtil.saveFile(filePicture,filePath,fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
